<template>
  <a-spin class="table-gl-con" style="margin-top: 10px" :loading="submitLoading">
    <TableWrap style="flex: 1" @refresh="getTableList">
      <template #headerLeft>
        <a-space>
          <p>共计 {{ total }} 条</p>
          <!-- SB活动不支持修改状态 -->
          <a-button class="gray-outline" size="medium" @click="changeStatus('ENABLED')" :disabled="advertStore.currentCampaign && advertStore.currentCampaign.adType === 'SPONSORED_BRANDS'">启用</a-button>
          <a-button class="gray-outline" size="medium" @click="changeStatus('PAUSED')" :disabled="advertStore.currentCampaign && advertStore.currentCampaign.adType === 'SPONSORED_BRANDS'">暂停</a-button>
          <a-button class="gray-outline" size="medium" @click="changeStatus('ARCHIVED')" :disabled="advertStore.currentCampaign && advertStore.currentCampaign.adType === 'SPONSORED_BRANDS'">归档</a-button>
          <!-- 暂时只支持SP活动新增商品 -->
          <a-button type="primary" size="medium" v-if="advertStore.currentCampaign && advertStore.currentCampaign.adType === 'SPONSORED_PRODUCTS'" @click="showAddProduct = true">新增商品</a-button>
        </a-space>
      </template>
      <template #tableBody>
        <a-table
          class="table-singe-line"
          ref="tableRef"
          row-key="id"
          :loading="tableLoading"
          @selection-change="selectColumn"
          :row-selection="rowSelection"
          :bordered="false"
          :data="tableList"
          :scroll="{
            x: '100%',
            y: '100%',
          }"
          size="mini"
          @sorter-change="sorterChange"
          :pagination="false"
        >
          <template #columns>
            <a-table-column :width="80" title="有效" fixed="left">
              <template #cell="{ record }">
                <a-popconfirm v-if="record.state != 'ARCHIVED'" :content="`确定是否${record.state === 'PAUSED' ? '开启' : '暂停'}商品`" @ok="changeState(record.state, record)" type="warning">
                  <a-switch v-model="record.state" :disabled="advertStore.currentCampaign && advertStore.currentCampaign.adType === 'SPONSORED_BRANDS'" size="medium" checked-value="ENABLED" unchecked-value="PAUSED" :beforeChange="handleChangeIntercept">
                    <template #checked> 开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                </a-popconfirm>
                <a-switch v-else v-model="record.state" disabled checked-value="ENABLED" unchecked-value="ARCHIVED" />
              </template>
            </a-table-column>
            <a-table-column :width="200" title="商品" fixed="left">
              <template #cell="{ record }">
                <div class="flex-c">
                  <ImgPopover :src="record.asinImageUrl || record.asinSmallImageUrl" :isPre="true">
                    <template #con>
                      <a-image width="40" :preview="false" height="40" fit="contain" :src="record.asinSmallImageUrl || record.asinImageUrl" />
                    </template>
                  </ImgPopover>
                  <div style="margin-left: 5px; width: 140px" class="highlight">
                    <a-typography-paragraph copyable :copy-text="record.asinUrl" style="margin-bottom: 0" :copy-tooltip-props="{ mini: true }">
                      <a-button style="line-height: 20px; height: 20px" type="text">{{ record.asin }}</a-button>
                    </a-typography-paragraph>
                    <TextLimit :rows="1">{{ record.sku }}</TextLimit>
                  </div>
                </div>
              </template>
            </a-table-column>
            <a-table-column :width="70" title="状态" fixed="left">
              <template #cell="{ record }">
                <p :class="$extract(statusMap[record.state], 'color')">{{ $extract(statusMap[record.state], 'name') }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="160" title="组合名称" fixed="left">
              <template #cell="{ record }">
                <TextLimit :rows="2">{{ record.portfolioName || '--' }}</TextLimit>
              </template>
            </a-table-column>
            <a-table-column :width="85" align="right" :sortable="sortable" data-index="impressions">
              <template #title>
                <a-popover content="广告曝光次数">
                  <p>
                    <span>曝光量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" align="right" :sortable="sortable" data-index="clicks">
              <template #title>
                <a-popover content="广告点击次数">
                  <p>
                    <span>点击量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CTR" align="right" :sortable="sortable" data-index="ctr">
              <template #title>
                <a-popover content="广告点击转化率=点击量/曝光量">
                  <p>
                    <span>CTR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="花费" align="right" :sortable="sortable" data-index="cost">
              <template #title>
                <a-popover content="亚马逊广告花费">
                  <p>
                    <span>花费</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cost || record.cost === 0">${{ Number(record.cost).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPC" align="right" :sortable="sortable" data-index="cpc">
              <template #title>
                <a-popover content="单次点击成本，CPC=广告花费/点击量">
                  <p>
                    <span>CPC</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="75" title="CVR" align="right" :sortable="sortable" data-index="cvr">
              <template #title>
                <a-popover content="广告转化率，CVR=广告订单量/点击量*100%">
                  <p>
                    <span>CVR</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" title="CPA" align="right" :sortable="sortable" data-index="cpa">
              <template #title>
                <a-popover content="单笔订单平均广告花费，CPA=广告花费/广告订单量">
                  <p>
                    <span>CPA</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.cpa || record.cpa === 0">${{ Number(record.cpa).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="总单量" align="right" :sortable="sortable" data-index="purchasesOrder">
              <template #title>
                <a-popover content="广告带来的订单及关联订单数量">
                  <p>
                    <span>总单量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesOrder || record.purchasesOrder === 0">{{ record.purchasesOrder }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="商品销量" align="right" :sortable="sortable" data-index="purchasesSale">
              <template #title>
                <a-popover content="广告商品销量">
                  <p>
                    <span>商品销量</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="95" title="销售额" align="right" :sortable="sortable" data-index="saleAmount">
              <template #title>
                <a-popover content="广告带来的销售额及关联销售额">
                  <p>
                    <span>销售额</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ACOS" align="right" :sortable="sortable" data-index="acos">
              <template #title>
                <a-popover content="投入产出比，ACOS=广告花费/广告销售额*100%">
                  <p>
                    <span>ACOS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.acos || record.acos === 0">{{ Number(record.acos).toFixed(2) }}%</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
            <a-table-column :width="85" title="ROAS" align="right" :sortable="sortable" data-index="roas">
              <template #title>
                <a-popover content="支出回报，ROAS=广告销售额/广告花费">
                  <p>
                    <span>ROAS</span>
                    <icon-question-circle />
                  </p>
                </a-popover>
              </template>
              <template #cell="{ record }">
                <p v-if="record.roas || record.roas === 0">{{ Number(record.roas).toFixed(2) }}</p>
                <p v-else>--</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
    <div class="pagination-footer">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-spin>
  <!-- 添加商品 -->
  <AddProduct v-if="showAddProduct" :isShow="showAddProduct" @closed="showAddProduct = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { getAdProductList, updateAdProduct } from '@/api/advert'
  import AddProduct from './addProduct.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { AdStatusHandle } from '../../types'
  import useAdvertStore from '@/store/modules/advert'
  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
  })
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const tableListMap = ref({})
  const showAddProduct = ref(false)
  const submitLoading = ref(false)
  const advertStore = useAdvertStore()
  const tableRef = ref()

  const statusMap = {
    ENABLED: { name: '投放中', color: 'success' },
    PAUSED: { name: '已暂停', color: 'normal' },
    ARCHIVED: { name: '已归档', color: 'gray' },
  }
  const showUserDialog = ref(false)
  const selectRows = ref<any>([])

  const selectColumn = (val: any) => {
    selectIds.value = val
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function getTableListByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 获取组合列表数据
  async function getTableList() {
    tableLoading.value = true
    const res: any = await getAdProductList({
      ...props.searchParams,
      ...searchVal.value,
    })
    tableLoading.value = false
    tableRef.value.selectAll(false)
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      el.id = el.shopId + el.campaignId + el.adId
      tableListMap.value[el.id] = el
    })
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.orderItems = null
    } else {
      searchVal.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }
  // 批量修改广告组状态
  function changeStatus(status: any) {
    if (!selectIds.value.length) {
      return Message.error('请选择商品')
    }
    Modal.confirm({
      title: '调整状态',
      content: `请再次确认，将选中的商品设置为${AdStatusHandle[status]}`,
      cancelText: '取消',
      okText: '确认',
      onOk: async () => {
        getSelectRows()
        requestUpdataState(selectRows.value, status, '设置成功')
      },
    })
    showUserDialog.value = true
  }
  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 单个修改广告组状态
  function changeState(state: any, item: any) {
    let status = state === 'PAUSED' ? 'ENABLED' : 'PAUSED'
    requestUpdataState([item], status)
  }
  //修改广告组状态请求
  async function requestUpdataState(list: Array<any>, state: string, msg?: string) {
    let params = list.map((el: any) => {
      return {
        adGroupId: el.adGroupId,
        campaignId: el.campaignId,
        adType: el.adType,
        shopId: el.shopId,
        state: state,
        asin: el.asin,
        adId: el.adId,
        adName: el.adName,
      }
    })
    submitLoading.value = true
    const res: any = await updateAdProduct(params)
    submitLoading.value = false
    if (!res) return
    getTableList()
    if (msg) {
      Message.success(msg)
    }
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  defineExpose({ getTableListByVal })
</script>
<style lang="less" scoped>
  .table-gl-con {
    height: 100%;
  }
  .gray {
    color: #999;
  }
  .success {
    color: rgb(var(--success-5));
  }
  .normal {
    color: var(--color-text-2);
  }
  :deep(.arco-table-sorter) {
    margin-left: 2px;
  }
  .popconfirm-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
</style>
